<script setup>
import { queryOperationalData } from '@/service/dashboard.js'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
const router = useRouter()
const operationalData = reactive({})
onMounted(async () => {
  const res = await queryOperationalData()
  Object.assign(operationalData, res.data)
  const salesAmountChart = echarts.init(salesAmountPictureRef.value)
// 销售额图表：突出「金额」的专业感（蓝色系+渐变+圆角柱形）
  const salesOption = {
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#409eff', // 边框色与图表主色一致
      borderWidth: 1,
      borderRadius: 8,
      padding: 12,
      boxShadow: '0 3px 12px rgba(64, 158, 255, 0.15)', // 阴影带主色倾向
      textStyle: { fontSize: 12, color: '#333' },
      formatter: function (params) {
        const { name: date, value: amount } = params
        const formattedAmount = amount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
        return `
        <div style="line-height: 1.8;">
          <div style="color: #666; margin-bottom: 4px;">日期：${date}</div>
          <div style="font-size: 15px; font-weight: 600; color: #2d8cf0;">
            销售额：¥${formattedAmount}
          </div>
        </div>
      `
      },
      emptyFormatter: () => '<div style="color: #999; font-size: 12px;">暂无销售额数据</div>',
      confine: true,
    },
    xAxis: {
      type: 'category',
      data: operationalData.dateList,
      axisLine: { lineStyle: { color: '#e8f4ff' } }, // 坐标轴颜色差异化
      axisLabel: { color: '#409eff', fontSize: 11 }, // x轴文字色与主色匹配
    },
    yAxis: {
      type: 'value',
      name: '销售额（元）',
      nameTextStyle: { fontSize: 11, color: '#409eff' },
      splitLine: {
        lineStyle: { type: 'dashed', color: '#e8f4ff', width: 1 } // 虚线颜色变浅
      },
      axisLine: { lineStyle: { color: '#e8f4ff' } },
      axisLabel: { color: '#666', fontSize: 10 }
    },
    series: [
      {
        type: 'bar', // 保留柱状图，但优化样式
        data: operationalData.salesAmountsData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [ // 纵向渐变
            { offset: 0, color: '#409eff' },
            { offset: 1, color: '#2d8cf0' }
          ]),
          borderRadius: [6, 6, 0, 0], // 仅顶部圆角，更精致
          borderWidth: 0
        },
        barWidth: '60%', // 柱形宽度调整
        label: { // 顶部显示数值（金额场景实用）
          show: true,
          position: 'top',
          fontSize: 10,
          color: '#2d8cf0',
          formatter: (params) => `¥${params.value.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',')}`
        }
      }
    ],
    grid: { left: '10%', right: '5%', bottom: '15%', top: '8%' } // 调整图表边距
  }
  salesAmountChart.setOption(salesOption)

  const userVisitsChart = echarts.init(userVisitedPicturePictureRef.value)
// 访问量图表：突出「流量」的活力（绿色系+折线+柱状组合）
  const visitsOption = {
    tooltip: {
      trigger: 'axis', // 改为axis触发（同时显示x轴同一位置所有数据）
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#52c41a', // 边框色改为绿色系
      borderWidth: 1,
      borderRadius: 8,
      padding: 12,
      boxShadow: '0 3px 12px rgba(82, 196, 26, 0.15)',
      textStyle: { fontSize: 12, color: '#333' },
      formatter: function (params) {
        const { name } = params[0]
        const value = params[0].value
        const formattedValue = value.toLocaleString()
        return `
        <div style="line-height: 1.8;">
          <div style="color: #666; margin-bottom: 4px;">日期：${name}</div>
          <div style="font-size: 15px; font-weight: 600; color: #48bb78;">
            ${formattedValue} 次访问
          </div>
        </div>
      `
      },
      emptyFormatter: () => '<div style="color: #999; font-size: 12px;">暂无访问数据</div>',
      confine: true,
    },
    xAxis: {
      type: 'category',
      data: operationalData.dateList,
      axisLine: { lineStyle: { color: '#f0f9f0' } }, // 绿色系坐标轴
      axisLabel: { color: '#48bb78', fontSize: 11 }
    },
    yAxis: {
      type: 'value',
      name: '访问人数（次）',
      nameTextStyle: { fontSize: 11, color: '#48bb78' },
      splitLine: {
        lineStyle: { type: 'dashed', color: '#f0f9f0', width: 1 }
      },
      axisLine: { lineStyle: { color: '#f0f9f0' } },
      axisLabel: { color: '#666', fontSize: 10 }
    },
    series: [
      {
        type: 'line', // 改为折线图（与柱状图形成核心差异）
        data: operationalData.userVisitsData,
        symbol: 'circle', // 标记点为圆形
        symbolSize: 6, // 标记点大小
        lineStyle: { color: '#48bb78', width: 3 }, // 线条加粗
        itemStyle: {
          color: '#fff',
          borderColor: '#48bb78',
          borderWidth: 2
        },
        areaStyle: { // 填充区域，增强视觉效果
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(72, 187, 120, 0.3)' },
            { offset: 1, color: 'rgba(72, 187, 120, 0.05)' }
          ])
        },
        label: { // 标记点显示数值
          show: true,
          position: 'top',
          fontSize: 10,
          color: '#48bb78',
          formatter: (params) => params.value.toLocaleString()
        }
      }
    ],
    grid: { left: '10%', right: '5%', bottom: '15%', top: '8%' }
  }
  userVisitsChart.setOption(visitsOption)

// 新增：窗口 resize 适配（可选，提升体验）
  window.addEventListener('resize', () => {
    salesAmountChart.resize()
    userVisitsChart.resize()
  })
})

function calculate(today, yesterday) {
  // 1. 处理参数为 undefined/null 的情况，默认转为 0
  const todayVal = today ?? 0
  const yesterdayVal = yesterday ?? 0

  // 2. 边界情况：昨日值为 0 时，返回 0.00（避免除数为 0）
  if (yesterdayVal === 0) {
    return 0.0
  }

  // 3. 核心计算：(今日值 - 昨日值) / 昨日值 × 100%
  const mom = ((todayVal - yesterdayVal) / yesterdayVal) * 100

  // 4. 四舍五入保留两位小数，确保返回数字类型（而非字符串）
  return Number(mom.toFixed(2))
}
function navigateToSpecificPage(param) {
  switch (param) {
    case 0:
      router.push({ name: 'ProductShowList' })
      break
    case 1:
      router.push({ path: '/customer/management' })
      break
    case 2:
      router.push({ name: 'order-process' })
      break
    case 3:
      router.push({ path: '/products/category' })
      break
    case 4:
      router.push({ name: 'Brand' })
      break
    case 5:
      router.push({ path: '/marketing/campaign/flash/sale' })
      break
    case 6:
      router.push({ path: '/marketing/campaign/coupon/list' })
      break
    default:
      ElMessage.warning('正在开发中')
  }
}
const salesAmountPictureRef = ref()
const userVisitedPicturePictureRef = ref()
</script>

<template>
  <div class="dashboard">
    <div class="dashboard-update-time">
      <div style="font-size: 20px; color: #333333">运营数据</div>
      <div style="font-size: 14px; color: #333333; margin-left: 20px">更新时间：{{ operationalData.updateTime }}</div>
    </div>
    <div class="dashboard-card-list">
      <div class="dashboard-card-list-item">
        <div class="dashboard-card-list-item-title">
          <div class="dashboard-card-list-item-title-left">成交订单（笔）</div>
          <div class="dashboard-card-list-item-title-right">今日</div>
        </div>
        <div class="dashboard-card-list-item-content">
          <div class="today-data">
            {{ operationalData.todayOrderCount }}
          </div>
          <div class="yesterday-data">
            <div>昨日 {{ operationalData.yesterdayOrderCount }}</div>
            <div style="margin-left: 16px; display: flex; align-items: center">
              <div>日环比</div>
              <div style="margin-left: 5px; margin-right: 10px">
                {{ calculate(operationalData.todayOrderCount, operationalData.yesterdayOrderCount) }}%
              </div>
              <div
                v-if="operationalData.todayOrderCount >= operationalData.yesterdayOrderCount"
                class="yesterday-data-arrow-up"
              ></div>
              <div v-else class="yesterday-data-arrow-down"></div>
            </div>
          </div>
          <div class="total-data">
            <div>成交订单总量（笔）</div>
            <div>{{ operationalData.totalOrderCount }}</div>
          </div>
        </div>
      </div>
      <div class="dashboard-card-list-item">
        <div class="dashboard-card-list-item-title">
          <div class="dashboard-card-list-item-title-left">销售金额（元）</div>
          <div class="dashboard-card-list-item-title-right">今日</div>
        </div>
        <div class="dashboard-card-list-item-content">
          <div class="today-data">
            {{ operationalData.todaySalesAmount }}
          </div>
          <div class="yesterday-data">
            <div>昨日 {{ operationalData.yesterdaySalesAmount }}</div>
            <div style="margin-left: 16px; display: flex; align-items: center">
              <div>日环比</div>
              <div style="margin-left: 5px; margin-right: 10px">
                {{ calculate(operationalData.todaySalesAmount, operationalData.yesterdaySalesAmount) }}%
              </div>
              <div
                v-if="operationalData.todaySalesAmount >= operationalData.yesterdaySalesAmount"
                class="yesterday-data-arrow-up"
              ></div>
              <div v-else class="yesterday-data-arrow-down"></div>
            </div>
          </div>
          <div class="total-data">
            <div>销售总额（元）</div>
            <div>{{ operationalData.totalSalesAmount }}</div>
          </div>
        </div>
      </div>
      <div class="dashboard-card-list-item">
        <div class="dashboard-card-list-item-title">
          <div class="dashboard-card-list-item-title-left">新增会员（人）</div>
          <div class="dashboard-card-list-item-title-right">今日</div>
        </div>
        <div class="dashboard-card-list-item-content">
          <div class="today-data">
            {{ operationalData.todayNewMemberCount }}
          </div>
          <div class="yesterday-data">
            <div>昨日 {{ operationalData.yesterdayNewMemberCount }}</div>
            <div style="margin-left: 16px; display: flex; align-items: center">
              <div>日环比</div>
              <div style="margin-left: 5px; margin-right: 10px">
                {{ calculate(operationalData.todayNewMemberCount, operationalData.yesterdayNewMemberCount) }}%
              </div>
              <div
                v-if="operationalData.todayNewMemberCount >= operationalData.yesterdayNewMemberCount"
                class="yesterday-data-arrow-up"
              ></div>
              <div v-else class="yesterday-data-arrow-down"></div>
            </div>
          </div>
          <div class="total-data">
            <div>会员总量（人）</div>
            <div>{{ operationalData.totalMemberCount }}</div>
          </div>
        </div>
      </div>
      <div class="dashboard-card-list-item">
        <div class="dashboard-card-list-item-title">
          <div class="dashboard-card-list-item-title-left">用户访问量（人）</div>
          <div class="dashboard-card-list-item-title-right">今日</div>
        </div>
        <div class="dashboard-card-list-item-content">
          <div class="today-data">
            {{ operationalData.todayUserVisits }}
          </div>
          <div class="yesterday-data">
            <div>昨日 {{ operationalData.yesterdayUserVisits }}</div>
            <div style="margin-left: 16px; display: flex; align-items: center">
              <div>日环比</div>
              <div style="margin-left: 5px; margin-right: 10px">
                {{ calculate(operationalData.todayUserVisits, operationalData.yesterdayUserVisits) }}%
              </div>
              <div
                v-if="operationalData.todayUserVisits >= operationalData.yesterdayUserVisits"
                class="yesterday-data-arrow-up"
              ></div>
              <div v-else class="yesterday-data-arrow-down"></div>
            </div>
          </div>
          <div class="total-data">
            <div>总用户访问量（人）</div>
            <div>{{ operationalData.totalUserVisits }}</div>
          </div>
        </div>
      </div>
    </div>
    <div class="quick-access-zone">
      <div class="quick-access-zone-title">快捷功能</div>
      <div class="quick-access-zone-content">
        <div class="quick-access-zone-content-item" @click="navigateToSpecificPage(0)">
          <div class="quick-access-zone-content-item-icon">
            <img alt="" src="@/assets/商品管理.svg" />
          </div>
          <div class="quick-access-zone-content-item-text">商品管理</div>
        </div>
        <div class="quick-access-zone-content-item" @click="navigateToSpecificPage(1)">
          <div class="quick-access-zone-content-item-icon">
            <img alt="" src="@/assets/会员管理.svg" />
          </div>
          <div class="quick-access-zone-content-item-text">会员管理</div>
        </div>
        <div class="quick-access-zone-content-item" @click="navigateToSpecificPage(2)">
          <div class="quick-access-zone-content-item-icon">
            <img alt="" src="@/assets/订单管理.svg" />
          </div>
          <div class="quick-access-zone-content-item-text">订单管理</div>
        </div>
        <div class="quick-access-zone-content-item" @click="navigateToSpecificPage(3)">
          <div class="quick-access-zone-content-item-icon">
            <img alt="" src="@/assets/分类管理.svg" />
          </div>
          <div class="quick-access-zone-content-item-text">分类管理</div>
        </div>
        <div class="quick-access-zone-content-item" @click="navigateToSpecificPage(4)">
          <div class="quick-access-zone-content-item-icon">
            <img alt="" src="@/assets/品牌管理.svg" />
          </div>
          <div class="quick-access-zone-content-item-text">品牌管理</div>
        </div>
        <div class="quick-access-zone-content-item" @click="navigateToSpecificPage(5)">
          <div class="quick-access-zone-content-item-icon">
            <img alt="" src="@/assets/秒杀管理.svg" />
          </div>
          <div class="quick-access-zone-content-item-text">秒杀管理</div>
        </div>
        <div class="quick-access-zone-content-item" @click="navigateToSpecificPage(6)">
          <div class="quick-access-zone-content-item-icon">
            <img alt="" src="@/assets/优惠券.svg" />
          </div>
          <div class="quick-access-zone-content-item-text">优惠券</div>
        </div>
        <div class="quick-access-zone-content-item" @click="navigateToSpecificPage(7)">
          <div class="quick-access-zone-content-item-icon">
            <img alt="" src="@/assets/财务管理.svg" />
          </div>
          <div class="quick-access-zone-content-item-text">财务</div>
        </div>
      </div>
    </div>
    <div class="sales-amount">
      <div class="sales-amount-title">近15天销售金额（元）</div>
      <div ref="salesAmountPictureRef" class="sales-amount-picture"></div>
    </div>
    <div class="user-visited-picture">
      <div class="user-visited-picture-title">近15天用户访问量（次）</div>
      <div ref="userVisitedPicturePictureRef" class="user-visited-picture-picture"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.dashboard {
  .dashboard-update-time {
    display: flex;
    padding: 10px;
    align-items: baseline;
    background-color: #fff;
  }

  .dashboard-card-list {
    display: grid;
    margin-top: 10px;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    gap: 15px;

    .dashboard-card-list-item {
      background-color: #fff;

      .dashboard-card-list-item-title {
        padding: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .dashboard-card-list-item-title-left {
          font-size: 14px;
        }

        .dashboard-card-list-item-title-right {
          font-size: 12px;
          padding: 0 10px;
          background-color: #eaf3ff;
          border: 1px #3a91fb solid;
          color: #3a91fb;
          border-radius: 30px;
          height: 20px;
          line-height: 20px;
        }
      }

      .dashboard-card-list-item-content {
        padding: 10px 15px;
        border-top: 1px solid #eaf3ff;

        .today-data {
          font-size: 36px;
          color: #666;
          padding: 5px 0 10px;
        }

        .yesterday-data {
          font-size: 14px;
          color: #606266;
          display: flex;

          .yesterday-data-arrow-up {
            width: 0;
            height: 0;
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            /* 底部边框有色，控制三角高度和颜色 */
            border-bottom: 10px solid #f53f3f;
          }

          .yesterday-data-arrow-down {
            width: 0;
            height: 0;
            /* 左右边框透明，形成底部尖角 */
            border-left: 6px solid transparent;
            border-right: 6px solid transparent;
            /* 顶部边框有色，控制三角高度和颜色 */
            border-top: 10px solid #0fc6c2; /* 颜色可自定义 */
          }
        }

        .total-data {
          margin-top: 20px;
          display: flex;
          justify-content: space-between;
          font-size: 14px;
          color: #666666;
        }
      }
    }
  }

  .quick-access-zone {
    background-color: #fff;
    margin-top: 15px;

    .quick-access-zone-title {
      font-size: 14px;
      color: #333;
      height: 42px;
      line-height: 42px;
      padding: 0 15px;
      border-bottom: 1px solid #f6f6f6;
      border-radius: 2px 2px 0 0;
    }

    .quick-access-zone-content {
      padding: 50px 20px;
      display: flex;
      justify-content: space-evenly;
      .quick-access-zone-content-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;
        .quick-access-zone-content-item-icon {
          img {
            width: 50px;
            height: 50px;
          }
        }
        .quick-access-zone-content-item-text {
          margin-top: 10px;
          font-size: 14px;
          color: #666666;
        }
      }
    }
  }
  .sales-amount {
    background-color: #fff;
    margin-top: 10px;
    padding: 10px 15px;
    .sales-amount-title {
      color: #666;
      font-size: 14px;
    }
    .sales-amount-picture {
      margin-top: 10px;
      width: 1300px;
      height: 400px;
    }
  }
  .user-visited-picture {
    background-color: #fff;
    margin-top: 10px;
    padding: 10px 15px;
    .user-visited-picture-title {
      color: #666;
      font-size: 14px;
    }
    .user-visited-picture-picture {
      margin-top: 10px;
      width: 1300px;
      height: 400px;
    }
  }
}
</style>
